<?php

declare(strict_types=1);

namespace app\controller\system;

use app\BaseController;
use app\service\system\file\Captcha;
use app\service\system\LoginService;
use owns\exception\TipsException;
use owns\facade\LoginLog;
use think\Exception;

/**
 * 管理员登录
 */
class Login extends BaseController
{
    /**
     * 图片验证码
     */
    public function getCaptcha()
    {
        return $this->success(make(Captcha::class)->generate());
    }
    /**
     * 登录
     */
    public function login()
    {
        $param = $this->request->post();

        $this->validate($param, [
            'username|登录帐号' => 'require|min:2|max:11',
            'password|登录密码' => 'require|length:6,64',
            //'captcha|验证码' => 'require|length:4',
            //'captchaId|验证码' => 'require',
        ]);
        $service = new LoginService();
        try {
            $user = $service->userLogin($param);
            // 返回信息
            $result['userInfo'] = $service->userInfo($user);
            $result['auth'] = $service->auth($user);
            $result['token'] = $service->generateToken($user);

            LoginLog::success($user->username);
            return $this->success($result);
        } catch (TipsException $e) {
            LoginLog::fail($param['username'], $e->getMessage());
            return $this->error($e->getMessage(), $e->getCode());
        } catch (Exception $e) {
            LoginLog::fail($param['username'], $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
}
